package com.garden.web.context.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

//@Configuration
public class RedisConfig {
    @Value("${redis.hostname}")
    private String redisHostname;
    @Value("${redis.port}")
    private String redisPort;

    //
    @Value("${redis.pool.maxActive}")
    private String maxActive;
    //
    @Value("${redis.pool.maxIdle}")
    private String maxIdle;
    //
    @Value("${redis.pool.maxWait}")
    private String maxWait;
    //
    @Value("${redis.pool.testOnBorrow}")
    private String testOnBorrow;
    //
    @Value("${redis.pool.testOnReturn}")
    private String testOnReturn;


    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisHostname);
        factory.setPort(Integer.parseInt(redisPort));
        factory.setPoolConfig(jedisPoolConfig());
        return factory;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate() {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(connectionFactory());
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(Integer.valueOf(maxIdle));
        jedisPoolConfig.setMaxTotal(Integer.valueOf(maxActive));
        jedisPoolConfig.setMaxWaitMillis(Integer.valueOf(maxWait));
        jedisPoolConfig.setTestOnBorrow(Boolean.valueOf(testOnBorrow));
        jedisPoolConfig.setTestOnReturn(Boolean.valueOf(testOnReturn));
        return jedisPoolConfig;
    }
}
